package com.alex;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.bykv.vk.openvk.api.proto.Bridge;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class AlexGromoreUtil {
    private static final String TAG = "AlexGromoreUtil";

    private static volatile boolean haveRefresh = false;
    private static final Object refreshLockObj = new Object();

    public static double getBestPriceInCacheNew(Object mbADObject) {
        Field[] fields = mbADObject.getClass().getDeclaredFields();
        double cpm = 0;
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object newmbAdObject = field.get(mbADObject);
                if (newmbAdObject != null) {
                    double findCpm = getBestPriceInCache(newmbAdObject);
                    if (findCpm > cpm) {
                        cpm = findCpm;
                    }
                }
            } catch (Throwable e) {

            }
        }
        return cpm / 100.0;

    }

    private static double getBestPriceInCache(Object mbADObject) {
        try {
            if (mbADObject != null) {
                List coreObjectList = getMBCoreObject(mbADObject);
                if (coreObjectList == null || coreObjectList.size() == 0) {
                    return 0;
                }

                for (Object coreObject : coreObjectList) {
                    if (coreObject != null) {
                        Class tempClass = coreObject.getClass();
                        Class targetClass = null;
                        while (tempClass != null && !tempClass.getName().equals("java.lang.Object")) {
                            if (tempClass.getSuperclass().getName().equals("java.lang.Object")) {
                                targetClass = tempClass;
                            }
                            tempClass = tempClass.getSuperclass();
                        }

                        if (targetClass != null) {
                            double price = 0;
                            price = fetchBestPriceByCacheList(targetClass, coreObject);
                            if (price > 0) {
                                return price;
                            }
                        }
                    }
                }
            }
        } catch (Throwable t) {
            printThrowableLog(t);
        }
        return 0.0;
    }

    private static List<Object> getMBCoreObject(Object mbADObject) {
        List<Object> coreObjectList = new ArrayList<>();
        try {
            Class tempClass = mbADObject.getClass();
            Field[] fields = tempClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object object = field.get(mbADObject);
                if (object == null) {
                    continue;
                }
                coreObjectList.add(object);
                Class fieldObjectClass = object.getClass();
                Field[] objectClassFields = fieldObjectClass.getDeclaredFields();
                for (Field nestField : objectClassFields) {
                    nestField.setAccessible(true);
                    Object nestObject = nestField.get(object);
                    coreObjectList.add(nestObject);
                }
            }
            return coreObjectList;
        } catch (Throwable t) {
            printThrowableLog(t);
        }
        return coreObjectList;
    }

    private static double fetchBestPriceByCacheList(Class targetClass, Object coreObject) {
        double bestPrice = 0;
        try {
            Class tempClass = coreObject.getClass().getSuperclass();
            while (!(tempClass instanceof Object)) {
                tempClass = tempClass.getSuperclass();
            }
        } catch (Throwable e) {

        }

        try {
            Field[] fields = targetClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object object = field.get(coreObject);
                if (object instanceof List<?>) {
                    if (object != null && (((List<?>) object).size()) > 0) {
                        for (Object listObject : ((List<?>) object)) {
//                            if ((listObject instanceof Bridge)) {
//                            }
                            double currentPrice = findEcpm(listObject);
                            if (currentPrice > bestPrice) {
                                bestPrice = currentPrice;
                            }

                        }

                    }
                }
            }
        } catch (Throwable t) {
            printThrowableLog(t);
        }
        return bestPrice;
    }


    private static double findEcpm(Object bridgeListObject) {
        double ecpm = 0;
        try {
            if (bridgeListObject != null) {
                Class<?> priceClass = bridgeListObject.getClass();
                Method getCpmMethod = priceClass.getMethod("getCpm");
                getCpmMethod.setAccessible(true);
                Object result = getCpmMethod.invoke(bridgeListObject);
                if (result instanceof Double) {
                    ecpm = (double) result;
                    if (ecpm > 0) {
                        return ecpm;
                    }
                }
            }
        } catch (Throwable e) {
        }

        if (bridgeListObject instanceof Bridge) {
            ArrayList<Field> fieldArrayList = new ArrayList<>();
            fillObjectField(bridgeListObject.getClass(), fieldArrayList);
            for (Field field : fieldArrayList) {
                if (field.getType() == double.class) {
                    try {
                        field.setAccessible(true);
                        double tempEcpm = (double) field.get(bridgeListObject);
                        if (ecpm <= tempEcpm) {
                            ecpm = tempEcpm;
                        }
                    } catch (Throwable e) {
                    }
                }
            }
        }
        return ecpm;
    }

    private static void fillObjectField(Class objectClass, List<Field> fieldList) {
        try {
            if (objectClass == null || objectClass.getName().equals(Object.class.getName())) {
                return;
            }
            Field[] field = objectClass.getDeclaredFields();
            if (field != null && field.length > 0) {
                fieldList.addAll(Arrays.asList(field));
            }

            fillObjectField(objectClass.getSuperclass(), fieldList);

        } catch (Throwable e) {

        }
    }


    private static void printThrowableLog(Throwable t) {
    }

    public static void fbPluginRefresh(Context context, Map<String, Object> map) {
        if(haveRefresh) {
            return;
        }
        synchronized (refreshLockObj) {
            //只在第一次初始化时设置
            if (!haveRefresh) {
                haveRefresh = true;
                try {
                    Object obj = map.get("forbid_gm_refresh");
                    boolean isForbidUpdate = true;
                    if (obj instanceof Boolean) {
                        isForbidUpdate = (boolean) obj;
                    }
                    if (isForbidUpdate) {
                        File file = new File(context.getFilesDir(), "pangle_p");
                        if (file.exists()) {
                            File file2 = new File(file.getAbsolutePath(), "com.byted.pangle.m");
                            if (file2.exists()) {
                                File[] listFiles = file2.listFiles(new FileFilter() {
                                    @Override // java.io.FileFilter
                                    public final boolean accept(File file) {
                                        return file != null && file.getName().matches("^version-(\\d+)$");
                                    }
                                });
                                if (listFiles == null || listFiles.length == 0) {
                                    return;
                                }

                                String[] split = AlexGromoreInitManager.getInstance().getNetworkVersion().split("\\.");
                                StringBuilder sb = new StringBuilder();
                                for (String str : split) {
                                    sb.append(str);
                                }
                                SharedPreferences.Editor edit = context.getSharedPreferences("pangle_meta_data_sp", Context.MODE_PRIVATE).edit();
                                int curSdkVersion = Integer.parseInt(sb.toString());
                                for (File file3 : listFiles) {
                                    int versionInt = Integer.parseInt(file3.getName().split("-")[1]);
                                    //当前集成版本不等于GM下发的热修复apk版本时，才设置成false去阻止热更新
                                    edit.putBoolean("INSTALLED_com.byted.pangle.m-" + versionInt, versionInt == curSdkVersion);
                                    edit.commit();
                                }
                            }
                        }
                    }
                } catch (Throwable e) {
                    Log.e(TAG, "fbPluginUpdate() >>> error: " + e.getMessage());
                }
            }
        }
    }
}
